package org.netty.message.client;

import java.net.InetSocketAddress;

import org.netty.message.gper.code.GpDecode;
import org.netty.message.gper.code.GpEncode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {
	
	private Bootstrap bootstrap;

    private Channel channel;

    private NioEventLoopGroup eventLoopGroup; 
    
    public static void main(String[] args) {
    	NettyClient client = new NettyClient();
    	client.start();
	}

	private void start() {
		// TODO Auto-generated method stub
		 eventLoopGroup = new NioEventLoopGroup();
	        bootstrap = new Bootstrap();
	        bootstrap.group(eventLoopGroup)
	                .channel(NioSocketChannel.class)
	                .handler(new ChannelInitializer<SocketChannel>() {
	                    @Override
	                    protected void initChannel(SocketChannel ch) throws Exception {
	                        ChannelPipeline pipeline = ch.pipeline();
	                        pipeline
	                        	//如果5秒没有写事件，触发心跳检测
	                        	.addLast(new IdleStateHandler(0,5,0))
	                            .addLast(new GpDecode())
	                            .addLast(new GpEncode())
	                            .addLast(new ClientHandler(NettyClient.this));
	                    }
	                });
	        // 发起连接，当连接断开时都要发起连接，也就是不停的调用这个方法
	        createConnect();
	}

	public void createConnect() {
		// TODO Auto-generated method stub
		// 如果连接没有断开，则什么也不做
        if(channel !=null && channel.isActive()){
            return;
        }
        final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 9000));
        try {
			channelFuture.addListener(new ChannelFutureListener() {
				
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					// TODO Auto-generated method stub
					if(channelFuture.isSuccess()){
                        channel = channelFuture.channel();
                        log.info("服务端连接成功");
                    }else {
                    	
                    }
				}
			}).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}

}
